﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Locations;
using Android.Provider;
using Android.Text;
using Android.Util;
using Android.Views;
using Android.Widget;
using Com.Baidu.Mapapi;
using Com.Baidu.Mapapi.Map;
using Java.IO;
using Environment = Android.OS.Environment;
using File = Java.IO.File;
using Uri = Android.Net.Uri;


namespace BaiduMapDemo
{
    public class CameraHelper
    {
        // private static File _file;
        private static File _dir;

        private static int ResizeHeight = 1600;
        private static int ResizeWidth = 1200;

        public static double WhRate = 0.75;

        static void CreateDirectoryForPictures()
        {
            //_file = new File(_dir, string.Format("t_{0}.jpg", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
            _dir = DeviceHelper.GetCreatePicDirectory();
        }

        private static void PostToAlbum(Context context, File file)
        {
            Intent mediascanIntent = new Intent(Intent.ActionMediaScannerScanFile);
            var contenturi = Uri.FromFile(file);
            mediascanIntent.SetData(contenturi);
            context.SendBroadcast(mediascanIntent);
        }

        public static File SaveToSdCard(Context context, byte[] data)
        {
            _dir = DeviceHelper.GetCreatePicDirectory();
            var _file = new File(_dir, string.Format("t_{0}.jpg", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
            using (var fs = new FileOutputStream(_file))
            {
                fs.Write(data);
            }

            //notify system album
            PostToAlbum(context, _file);
            return _file;
        }

      

        public static Bitmap LoadAndResizeBitmap(byte[] imgData, int width, int height)
        {
            // First we get the the dimensions of the file on disk
            BitmapFactory.Options options = new BitmapFactory.Options { InJustDecodeBounds = true };
            BitmapFactory.DecodeByteArray(imgData, 0, imgData.Length, options);

            // Next we calculate the ratio that we need to resize the image by
            // in order to fit the requested dimensions.
            int outHeight = options.OutHeight;
            int outWidth = options.OutWidth;
            int inSampleSize = 1;

            if (outHeight > height || outWidth > width)
            {
                inSampleSize = outWidth > outHeight
                                   ? outHeight / height
                                   : outWidth / width;
            }

            // Now we will load the image and have BitmapFactory resize it for us.
            options.InSampleSize = inSampleSize;
            options.InJustDecodeBounds = false;
            Bitmap resizedBitmap = BitmapFactory.DecodeByteArray(imgData, 0, imgData.Length, options);
            return resizedBitmap;
        }

        public static Task<File> SaveToSdCardAsync(Context context, byte[] data)
        {
            return Task.Factory.StartNew(() =>
            {
                return SaveToSdCard(context, data);
            });
        }
    

        public static Task<File> SaveToSdCardAsync(Bitmap bitmap)
        {
            return Task.Factory.StartNew(() =>
            {
                return saveBitmap(bitmap);
            });
        }

        public static File saveBitmap(Bitmap bitmap)
        {
            _dir = DeviceHelper.GetCreatePicDirectory();
            var _file = new File(_dir, string.Format("cat_{0}.png", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
            try
            {
                using (var fs = new FileStream(_file.AbsolutePath, FileMode.CreateNew))
                {
                    //Bitmap.CreateScaledBitmap()
                    //bitmap.EraseColor(Color.Black);
                    bitmap.Compress(Bitmap.CompressFormat.Png, 85, fs);

                    fs.Flush(true);

                }
                bitmap.Recycle();
            }
            catch (Exception ex)
            {
                Log.Debug("CameraHelper:ss:", ex.Message);
            }
            return _file;
        }

       
    }

    public class BaiduMapCapture : Java.Lang.Object, IMKMapViewListener,IDisposable
    {
        public event EventHandler<BmapCaptureEventArgs> CaptureSnaped;

        protected virtual void OnCaptureSnaped(BmapCaptureEventArgs e)
        {
            EventHandler<BmapCaptureEventArgs> handler = CaptureSnaped;
            if (handler != null) handler(this, e);
        }

        private MapView map;
        private View view;
        public BaiduMapCapture(View target,MapView mapview,BMapManager bmapmanager)
        {
            map = mapview;
            view = target;
            map.RegMapViewListener(bmapmanager, this);            
        }

        public void OnClickMapPoi(MapPoi p0)
        {
           
        }

        public void OnGetCurrentMap(Bitmap p0)
        {
            var img=view.CaptureSnap(p0);
            OnCaptureSnaped(new BmapCaptureEventArgs() { Image = img });
        }

        public void OnMapAnimationFinish()
        {
           
        }

        public void OnMapMoveFinish()
        {
          
        }

        public void Dispose()
        {
            base.Dispose();
        }

        public void StartCap()
        {
            var tmp=map.CurrentMap;
            Log.Debug("BMAP:", tmp.ToString());
        }
    }

    public class BmapCaptureEventArgs : EventArgs
    {
        public Bitmap Image { get; set; }
    }

    public static class BitMapHelp
    {
        public static Bitmap CaptureSnap(this View view)
        {
            // var pic = Bitmap.CreateBitmap(width, height, Android.Graphics.Bitmap.Config.Argb8888);
            bool isDcEnabled = view.DrawingCacheEnabled;

            if (!isDcEnabled)
            {
                view.DrawingCacheEnabled = true;
            }

            var willNotcacheDrawing = view.WillNotCacheDrawing();
            view.SetWillNotCacheDrawing(false);

            var bcolor = view.DrawingCacheBackgroundColor;
            if (bcolor != 0)
            {
                view.DestroyDrawingCache();
            }
            view.DrawingCacheBackgroundColor = Color.Transparent;

            view.BuildDrawingCache();

            var pic = view.DrawingCache;

            var myImg = Bitmap.CreateBitmap(pic);

            view.DestroyDrawingCache();
            view.SetWillNotCacheDrawing(willNotcacheDrawing);

            view.DrawingCacheEnabled = isDcEnabled;
            return myImg;
        }

        public static byte[] CaptureSnapBytes(this View view)
        {
            var img = view.CaptureSnap();
            byte[] tmp;
            using (MemoryStream ms = new MemoryStream())
            {
                img.Compress(Bitmap.CompressFormat.Png, 100, ms);
                tmp = new byte[ms.Length];
                ms.Read(tmp, 0, (int)ms.Length);
            }
            img.Recycle();
            return tmp;
        }

        public static Bitmap CaptureSnap(this View view,Bitmap mapBitmap)
        {
            // var pic = Bitmap.CreateBitmap(width, height, Android.Graphics.Bitmap.Config.Argb8888);
            bool isDcEnabled = view.DrawingCacheEnabled;

            if (!isDcEnabled)
            {
                view.DrawingCacheEnabled = true;
            }

            var willNotcacheDrawing = view.WillNotCacheDrawing();
            view.SetWillNotCacheDrawing(false);

            var bcolor = view.DrawingCacheBackgroundColor;
            if (bcolor != 0)
            {
                view.DestroyDrawingCache();
            }
            view.DrawingCacheBackgroundColor = Color.Transparent;

            view.BuildDrawingCache();

            var pic = view.DrawingCache;

            var myImg = Bitmap.CreateBitmap(pic);
            view.DestroyDrawingCache();
            view.SetWillNotCacheDrawing(willNotcacheDrawing);

            view.DrawingCacheEnabled = isDcEnabled;

            Bitmap b = Bitmap.CreateBitmap(myImg.Width, myImg.Height, Bitmap.Config.Argb8888);
            Canvas c = new Canvas(b);
            c.DrawBitmap(myImg,0,0,null);
            c.DrawBitmap(mapBitmap,0,0,null);
            var fontPaint = new Paint();
            fontPaint.Color = Color.Blue;
            fontPaint.SetTypeface(Typeface.SansSerif);
            fontPaint.AntiAlias = true;
            fontPaint.FilterBitmap = true;
            fontPaint.TextSize = 20;

            c.DrawText("哈哈哈", 20, 40, fontPaint);
            c.Save(SaveFlags.All);
            c.Restore();
            myImg.Recycle();
            mapBitmap.Recycle();
            return b;
        }


        public static void CaptureSnap(this View view,MapView mapview,BMapManager bmapmanager,Action<Bitmap> onSnaped)
        {
            // var pic = Bitmap.CreateBitmap(width, height, Android.Graphics.Bitmap.Config.Argb8888);
           BaiduMapCapture bmc=new BaiduMapCapture(view,mapview,bmapmanager);
            bmc.StartCap();
           bmc.CaptureSnaped += delegate (object s, BmapCaptureEventArgs e)
           {
               onSnaped(e.Image);
           };
        }

        public static byte[] CaptureSnapBytes(this View view,Bitmap mapBitmap)
        {
            var img = view.CaptureSnap(mapBitmap);
            byte[] tmp;
            using (MemoryStream ms = new MemoryStream())
            {
                img.Compress(Bitmap.CompressFormat.Png, 100, ms);
                tmp = new byte[ms.Length];
                ms.Read(tmp, 0, (int)ms.Length);
            }
            img.Recycle();
            return tmp;
        }
    }

    public class DeviceHelper
    {
        public const int OpenGPS = 201;

        public static bool InitGPS(Context context)
        {
            var locationManager = context.GetSystemService(Context.LocationService) as LocationManager;

            if (locationManager.IsProviderEnabled(LocationManager.GpsProvider))
            {
                return true;
            }

            Intent i = new Intent(Settings.ActionLocationSourceSettings);
            ((Activity)context).StartActivityForResult(i, OpenGPS);
            return false;
        }

        public static bool GPSOpen(Context context)
        {
            var locationManager = context.GetSystemService(Context.LocationService) as LocationManager;

            if (locationManager.IsProviderEnabled(LocationManager.GpsProvider))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 据两个点,计算距离,结果为公里,若换算成英里:result ÷ 1.609344.换算成海里:(result÷1.609344)×0.8684
        /// </summary>
        /// <param name="latitude1"></param>
        /// <param name="longitude1"></param>
        /// <param name="latitude2"></param>
        /// <param name="longitude2"></param>
        /// <returns></returns>
        public static float ComputeDistance(double latitude1, double longitude1, double latitude2, double longitude2)
        {
            float[] resultes = new float[1];
            Location.DistanceBetween(latitude1, longitude1, latitude2, longitude2, resultes);
            //  结果为英里,若换算成公里:result × 1.609344.换算成海里:result×0.8684
            return resultes[0] * 1.609344f;
        }

        /// <summary>
        /// 检测是否存在SD卡
        /// </summary>
        /// <returns></returns>
        public static bool SdCardExists()
        {
            return Android.OS.Environment.ExternalStorageState.Equals(Android.OS.Environment.MediaMounted);
        }

        public static Java.IO.File GetCreatePicDirectory()
        {
            // var file= new File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim), "tenmini");
            var file = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory, "/Tenmini/DCIM/");
            if (!file.Exists())
            {
                file.Mkdirs();
            }
            return file;
        }
    }
}
